'''
@version: python3
@author: ‘eric‘
@license: Apache Licence
@contact: steinven@qq.com
@software: PyCharm
@file: tt.py
@time: 2023-09-28 17:40
'''
# -*- coding: utf-8 -*-
# flake8: noqa
import configparser
import os
import sys
import uuid

from loguru import logger

# 创建 ConfigParser 实例
from qiniu import Auth, BucketManager

config = configparser.ConfigParser()

# 读取配置文件
if getattr(sys, 'frozen', False):
    BASE_DIR = os.path.dirname(sys.executable)
elif __file__:
    BASE_DIR = os.path.dirname(os.path.dirname(__file__))
config.read(os.path.join(BASE_DIR,'config.ini'),encoding='utf-8')  # 替换为您的配置文件路径


url_preffix = config.get('qiniu', 'url_preffix')
access_key = config.get('qiniu', 'access_key')
secret_key = config.get('qiniu', 'secret_key')
bucket_name = config.get('qiniu', 'bucket_name')
expire_time = int(config.get('qiniu', 'expire_time'))


def upload2qiniu(local_file,upload_path):
    '''
    上传文件到qiniu
    Parameters
    ----------
    local_file  待上传文件路径
    oss_file_name   保存到oss中的文件路径
    upload_path oss目录

    Returns
    -------
    (上传结果,oss链接)
    '''
    from qiniu import Auth, put_file, etag
    # from pathlib import Path
    # file_ext = Path(local_file).suffix
    file_name = os.path.basename(local_file)


    # 构建鉴权对象
    q = Auth(access_key, secret_key)

    # 上传后保存的文件名
    key = f'{upload_path}/{file_name}'

    # 生成上传 Token，可以指定过期时间等
    token = q.upload_token(bucket_name, key, expire_time)

    ret, info = put_file(token, key, local_file, version='v2')
    logger.debug('info：%s' % info)
    try:
        key = ret['key']
        return True,f'{url_preffix}{key}'
    except:
        logger.error(f'{local_file}上传失败')
        logger.error(info)
        return False, ''


def is_file_processed(file_name):
    '''
    检查文件是否存在（是否已处理过）
    :param file_name:
    :return:
    '''
    q = Auth(access_key, secret_key)
    # 初始化BucketManager
    bucket = BucketManager(q)
    # 你要测试的空间， 并且这个key在你空间中存在
    key = f'after/{file_name}'
    # 获取文件的状态信息
    ret, info = bucket.stat(bucket_name, key)
    logger.info(ret)
    logger.info(info)
    try:
        return ret['fsize']
    except:
        logger.info(f'is_file_processed-q七牛云{is_file_processed}')
        return

if __name__ == '__main__':
    upload2qiniu(r'D:\pdi\1\transfer.ktr','after')
